package com.jason.library.common.util

import android.app.Activity
import android.content.Context
import android.graphics.Rect
import android.os.Handler
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import android.view.inputmethod.InputMethodManager

object KeyboardUtils {

    /**
     * 显示输入方
     */
    fun showInputMethod(
        context: Context,
        editText: View?
    ) {
        val handler = Handler()
        if (editText != null) {
            editText.isFocusable = true
            editText.requestFocus()
        }
        handler?.postDelayed({
            try {
                val imm = context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(editText, 0)
            } catch (e: Exception) {
            }
        }, 200)
    }

    fun hideInputKeyboard(context: Context?) {
        if (context != null) {
            val imm = context
                .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (imm != null) {
                val view = (context as Activity).currentFocus
                if (view != null) {
                    imm.hideSoftInputFromWindow(view.windowToken, 0)
                }
            }
        }
    }

    /**
     * 监听软键盘缩放
     * @param activity
     * @param listener
     */
    fun observeSoftKeyboard(
        activity: Activity,
        listener: OnSoftKeyboardChangeListener
    ) {
        val decorView = activity.window.decorView
        decorView.viewTreeObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener {
            var previousKeyboardHeight = -1
            override fun onGlobalLayout() {
                val rect = Rect()
                decorView.getWindowVisibleDisplayFrame(rect)
                val displayHeight = rect.bottom - rect.top
                val height = decorView.height
                val keyboardHeight = height - displayHeight
                if (previousKeyboardHeight != keyboardHeight) {
                    val hide = displayHeight.toDouble() / height > 0.8
                    listener.onSoftKeyBoardChange(keyboardHeight, !hide)
                }
                previousKeyboardHeight = height
            }
        })
    }

    interface OnSoftKeyboardChangeListener {
        fun onSoftKeyBoardChange(softKeyboardHeight: Int, visible: Boolean)
    }
}